package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.context.BaseContext;
import com.sky.dto.OrdersCancelDTO;
import com.sky.dto.OrdersPageQueryDTO;
import com.sky.dto.OrdersRejectionDTO;
import com.sky.dto.OrdersSubmitDTO;
import com.sky.entity.AddressBook;
import com.sky.entity.OrderDetail;
import com.sky.entity.Orders;
import com.sky.entity.ShoppingCart;
import com.sky.exception.AddressBookBusinessException;
import com.sky.exception.OrderBusinessException;
import com.sky.exception.ShoppingCartBusinessException;
import com.sky.mapper.AddressBookMapper;
import com.sky.mapper.OrderMapper;
import com.sky.mapper.ShoppingCartMapper;
import com.sky.result.PageResult;
import com.sky.service.OrderService;
import com.sky.vo.OrderStatisticsVO;
import com.sky.vo.OrderSubmitVO;
import com.sky.vo.OrderVO;
import com.sky.websocket.WebSocketServer;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author zhangyu
 * @data 2023/4/24 17:42
 */
@Service
public class OrderServiceImpl implements OrderService {
    @Autowired
    private AddressBookMapper addressBookMapper;
    @Autowired
    private ShoppingCartMapper shoppingCartMapper;
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private WebSocketServer webSocketServer;

    /**
     * 用户下单
     *
     * @param ordersSubmitDTO
     */
    @Override
    public OrderSubmitVO addOrder(OrdersSubmitDTO ordersSubmitDTO) {
        Long userId = BaseContext.getCurrentId();
        AddressBook addressBookById = addressBookMapper.getById(ordersSubmitDTO.getAddressBookId());
        if (addressBookById == null) {
            throw new AddressBookBusinessException(MessageConstant.ADDRESS_BOOK_IS_NULL);
        }
        ShoppingCart shoppingCart = new ShoppingCart();
        shoppingCart.setUserId(userId);
        List<ShoppingCart> shoopingCarts = shoppingCartMapper.getShoopingCartByUserId(shoppingCart);
        if (shoopingCarts == null || shoopingCarts.size() == 0) {
            throw new ShoppingCartBusinessException(MessageConstant.SHOPPING_CART_IS_NULL);
        }
        //前面判断确定无误后开始进行下单操作
        Orders orders = new Orders();
        //字段比较多,检查还有哪些需要补上
        BeanUtils.copyProperties(ordersSubmitDTO, orders);
        orders.setStatus(Orders.PENDING_PAYMENT);
        orders.setConsignee(addressBookById.getConsignee());
        orders.setAddress(addressBookById.getDistrictName());
        orders.setPhone(addressBookById.getPhone());
        orders.setUserId(userId);
        orders.setPayStatus(Orders.UN_PAID);
        orders.setOrderTime(LocalDateTime.now());
        orders.setNumber(String.valueOf(System.currentTimeMillis()));
        orderMapper.addOrder(orders);
        Long orderId = orders.getId();
        for (ShoppingCart shoopingCart : shoopingCarts) {
            OrderDetail orderDetail = new OrderDetail();
            BeanUtils.copyProperties(shoopingCart, orderDetail);
            orderDetail.setOrderId(orderId);
            orderMapper.addOrderDetail(orderDetail);
        }
        //下单完成,根据当前用户id清空购物车
        shoppingCartMapper.deleteShoppingByUserId(userId);

        return OrderSubmitVO.builder().id(userId).orderNumber(orders.getNumber())
                .orderAmount(orders.getAmount()).orderTime(orders.getOrderTime()).build();
    }


    @Override
    public void getOrderAgain(Long id) {
        /*Orders orderAgain = orderMapper.getOrderAgain(id);
        orderAgain.setNumber(String.valueOf(System.currentTimeMillis()));
        orderAgain.setOrderTime(LocalDateTime.now());
        orderAgain.setId(null);
        orderAgain.setEstimatedDeliveryTime(LocalDateTime.now().plusHours(1));
        orderMapper.addOrder(orderAgain);
        //根据订单id查询订单详情并跟随订单表一起增加
        List<OrderDetail> orderDetailByOrderId = orderMapper.getOrderDetailByOrderId(id);
        for (OrderDetail orderDetail : orderDetailByOrderId) {
            orderDetail.setOrderId(null);
            orderDetail.setOrderId(orderAgain.getId());
        }
        orderDetailByOrderId.forEach(orderDetail -> {
            orderMapper.addOrderDetail(orderDetail);
        });*/
        List<OrderDetail> orderDetailByOrderId = orderMapper.getOrderDetailByOrderId(id);
        for (OrderDetail orderDetail : orderDetailByOrderId) {
            ShoppingCart shoppingCart=new ShoppingCart();
            BeanUtils.copyProperties(orderDetail,shoppingCart);
            shoppingCart.setUserId(BaseContext.getCurrentId());
            shoppingCart.setCreateTime(LocalDateTime.now());
            shoppingCartMapper.insertShoppingCart(shoppingCart);
        }
    }

    @Override
    public PageResult selectAllOrders(OrdersPageQueryDTO ordersPageQueryDTO) {
        PageHelper.startPage(ordersPageQueryDTO.getPage(), ordersPageQueryDTO.getPageSize());
        Page<Orders> ordersPage = orderMapper.getOrdersPage(ordersPageQueryDTO);
        List<OrderVO> orderVo = getOrderVo(ordersPage);
        return new PageResult(ordersPage.getTotal(),orderVo);

    }

    //建立OrderVo
    public List<OrderVO> getOrderVo(Page<Orders> ordersPage) {

        List<OrderVO> orderVOS = new ArrayList<>();
        List<Orders> orders = ordersPage.getResult();
        for (Orders order : orders) {
            OrderVO orderVO = new OrderVO();
            BeanUtils.copyProperties(order, orderVO);
            orderVO.setOrderDishes(Piece(order.getId()));
            orderVO.setOrderDetailList(orderMapper.getOrderDetailByOrderId(order.getId()));
            orderVOS.add(orderVO);
        }
        return orderVOS;
    }

    //开始拼接订单详情表里面的菜品名字和数量
    public String Piece(Long id) {
        List<OrderDetail> orderDetailByOrderId = orderMapper.getOrderDetailByOrderId(id);
        String str = null;
        for (OrderDetail orderDetail : orderDetailByOrderId) {
            str = str + orderDetail.getName() + "*" + orderDetail.getNumber();
        }
        return str;
    }

    @Override
    public OrderVO selectOrderDetailByOrderId(Long id) {
        OrderVO orderVO=new OrderVO();
        Orders order = orderMapper.getOrderById(id);
        List<OrderDetail> orderDetailByOrderId = orderMapper.getOrderDetailByOrderId(id);
        BeanUtils.copyProperties(order,orderVO);
        orderVO.setOrderDetailList(orderDetailByOrderId);
        return orderVO;
    }

    @Override
    public void cancelOrder(Long id) {
        orderMapper.cancelOrder(id);
    }
    /***************************************商家端**********************************************/
    @Override
    public PageResult selectOrders(OrdersPageQueryDTO ordersPageQueryDTO) {
        PageHelper.startPage(ordersPageQueryDTO.getPage(),ordersPageQueryDTO.getPageSize());
        Page<Orders> ordersPage = orderMapper.getOrdersPage(ordersPageQueryDTO);
        List<OrderVO> orderVOS=new ArrayList<>();
        List<Orders> orders = ordersPage.getResult();
        for (Orders order : orders) {
            OrderVO orderVO=new OrderVO();
            BeanUtils.copyProperties(order,orderVO);
           orderVO.setOrderDishes( Piece(order.getId()));
           orderVOS.add(orderVO);
        }
        return new PageResult(ordersPage.getTotal(),orderVOS);
    }

    @Override
    public OrderStatisticsVO getOrderStatus() {
        //待接单
        Integer toBeConfirmeds = orderMapper.getOrderStatus(Orders.TO_BE_CONFIRMED);
        //待派送
        Integer  confirmeds= orderMapper.getOrderStatus(Orders.CONFIRMED);
        //派送中数量
        Integer deliveryInProgress=orderMapper.getOrderStatus(Orders.DELIVERY_IN_PROGRESS);
        OrderStatisticsVO orderStatisticsVO=new OrderStatisticsVO();
        orderStatisticsVO.setToBeConfirmed(toBeConfirmeds);
        orderStatisticsVO.setToBeConfirmed(confirmeds);
        orderStatisticsVO.setDeliveryInProgress(deliveryInProgress);
        return orderStatisticsVO;
    }

    @Override
    public OrderVO selectOrderDetails(Long id) {
        Orders order = orderMapper.getOrderById(id);
        List<OrderDetail> orderDetailByOrderId = orderMapper.getOrderDetailByOrderId(id);
        OrderVO orderVO=new OrderVO();
        BeanUtils.copyProperties(order,orderVO);
        orderVO.setOrderDetailList(orderDetailByOrderId);
        return orderVO;

    }

    @Override
    public void confirmOrder(Long id) {
        Orders orders=new Orders();
        orders.setId(id);
        orders.setStatus(Orders.CONFIRMED);
        orderMapper.update(orders);
    }

    @Override
    public void rejection(OrdersRejectionDTO ordersRejectionDTO) {
        Orders orders=new Orders();
        orders.setId(ordersRejectionDTO.getId());
        orders.setStatus(Orders.CANCELLED);
        orders.setRejectionReason(ordersRejectionDTO.getRejectionReason());
        orderMapper.update(orders);
    }

    @Override
    public void cancel(OrdersCancelDTO ordersCancelDTO) {
        Orders orders=new Orders();
        orders.setId(ordersCancelDTO.getId());
        orders.setStatus(Orders.CANCELLED);
        orders.setCancelReason(ordersCancelDTO.getCancelReason());
        orderMapper.update(orders);
    }

    @Override
    public void Delivery(Long id) {
        Orders orders=new Orders();
        orders.setStatus(Orders.DELIVERY_IN_PROGRESS);
        orders.setId(id);
        orderMapper.update(orders);
    }

    @Override
    public void complete(Long id) {
        Orders orders=new Orders();
        orders.setStatus(Orders.COMPLETED);
        orders.setId(id);
        orderMapper.update(orders);
    }

    @Override
    public void reminder(Long id) {
        Orders order = orderMapper.getOrderById(id);
        if(order==null){
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
        }
        Map map=new HashMap();
        map.put("type",2);
        map.put("orderId",id);
        map.put("content","订单号:"+order.getNumber());
        webSocketServer.sendToAllClient(JSON.toJSONString(map));
    }
}
